

import os
import sys
import datetime
import subprocess
from pprint import pprint

from externals.pyconfig import PyConfig
from tools import shortcut


DIR_META = "_simpledms.meta"
FILE_META_EXT = ".meta"

META_CREATE_DATE = "meta create date"
ITEM_CREATE_DATE = "item create date"


class FilesystemItem(object):
    FILE = "file"
    DIR = "directory"
    def __init__(self, cmd_arg):

        self.path = os.path.normpath(cmd_arg)
        self.abspath = os.path.abspath(self.path)

        if os.path.isfile(self.path):
            self.fs_type=self.FILE
            basename, ext = os.path.splitext(self.path)
            if ext == ".meta":
                raise SkipMetaFile("Skip %r" % self.path)
            self.meta_filename = basename + FILE_META_EXT
        elif os.path.isdir(self.path):
            self.fs_type=self.DIR
            self.meta_filename = os.path.join(self.path, DIR_META)
        else:
            raise UnknownTypeError(cmd_arg)

        stat = os.stat(self.path)
        mtime = stat.st_mtime
        mdatetime = datetime.datetime.utcfromtimestamp(mtime)

        self.meta = PyConfig(
            filename=self.meta_filename, verbose=1,
            defaults = {
                META_CREATE_DATE: datetime.datetime.now(),
                ITEM_CREATE_DATE: mdatetime,
            }
        )
        self.meta.debug()

    def delete_metafile(self):
        """
        Delete the metafile.
        """
        print "Delete %r..." % self.meta_filename,
        try:
            os.remove(self.meta_filename)
        except Exception, err:
            print "Error: %s" % err
        else:
            print "Ok"

    #--------------------------------------------------------------------------

    def virtualize(self, outpath):
        if not os.path.isdir(outpath):
            os.mkdir(outpath)

        basename = os.path.split(self.path)[1]
        outpath = os.path.join(outpath, basename)
        
        if self.fs_type == self.FILE:
            method = os.link
        else:
            method = os.symlink
        
        print "%s:" % method.__name__
        print self.abspath
        print "to"
        print outpath

        output = None
        try:
            output = method(self.abspath, outpath)
        except Exception, err:
            print "Error: %r" % err
        else:
            print "Ok"
            
        if output: # Windows symlink only ;)
            print "-"*79
            print output.strip()
            print "-"*79

    def debug(self):
        print "_"*79
        print "FilesystemItem debug:"
        pprint(self.__dict__)
        print "-"*79

    def __repr__(self):
        return "%r (%s)" % (self.path, self.fs_type)



class FilesystemItemError(Exception):
    """ main error class for all FilesystemItem errors """
    pass


class UnknownTypeError(FilesystemItemError):
    def __init__(self, path):
        self.path = path

    def __repr__(self):
        return u"filesystem item %r is unknown or doesn't exist!" % self.path

    __str__ = __repr__

class SkipMetaFile(FilesystemItemError):
    """ Skip all .meta files """
    pass